var mqtt = require('mqtt/dist/mqtt.js')
const MQTT_IP = 'platform.xibushigu.com/ws'//mqtt地址端口
const MQTT_OPTIONS = {
    connectTimeout: 5000,
    clientId: '1241235',
    username: 'guest',
    password: 'guest',
    clean: false
}

let heartbeatInterval=null


let client = null;
const initMqtt = function (cId='') {
    if (cId!==''){
        MQTT_OPTIONS.clientId=cId
    }else {
        let date = new Date().getTime();
        MQTT_OPTIONS.clientId='mqttid'+date
    }

    // #ifdef H5
    client = mqtt.connect('wss://'+MQTT_IP,MQTT_OPTIONS)
    // #endif
    // #ifdef MP-WEIXIN||APP-PLUS
    client = mqtt.connect('wxs://'+MQTT_IP,MQTT_OPTIONS)
    // #endif

    client.on('connect', () => {
        console.log('连接成功');
        heartbeatInterval=setInterval(()=>{
            sendHeartbeat()
        },19*1000)

    });
    client.on('message', (topic, payload) => {
        //在这里做处理：收到新消息走这个方法
        console.log('更新', topic + ':' + payload);
    });
    client.on('disconnect', () => {
        console.log('代理断开连接');
    });
    client.on('close', () => {
        console.log('断开连接');
    });
    client.on('offline', () => {
        console.log('脱机');
    });
    client.on('error', () => {
        console.log('无法连接');
        initMqtt();
    });
};
//添加订阅 ${$GLOBAL.MQTT_TOPIC}/user/${userId}订阅的主题地址：问后端，是直接返回还是拼接
const addSubscription = function (topicName) {
    client.subscribe(topicName, err => {
        if (!err) {
            console.log('订阅成功');
        } else {
            console.log('订阅失败');
        }
    });
}

function sendHeartbeat() {
    // client.send('pong')
    client.publish('ping')
}


const closeMqtt=function (cid) {

}

const mqttFun = {
    initMqtt,
    addSub:addSubscription,
};

const install = (Vue) => {
    Vue.prototype.mqtt=mqttFun
}

export default {
    install
}
